// pages/welcome/welcome.js
import apiConfig from "../../utils/api.js";

Page({
  data: {
    imgBaseUrl: "",
    iconBaseUrl: "",
    isLogout: true,
    avatarUrl: "",
    nickname: "",
    showLoginModal: false,
    welcomeImage: "",
  },

  onLoad() {
    this.loadData();
  },
  onShow() {
    this.loadData();
  },

  loadData() {
    this.setData({
      imgBaseUrl: apiConfig.ENV.imgBaseUrl || "",
      iconBaseUrl: apiConfig.ENV.iconBaseUrl,
    });
    // 可选欢迎图
    this.setData({ welcomeImage: this.data.iconBaseUrl + "icon-school.jpg" });

    const userinfo = wx.getStorageSync("userInfo");
    const isLogout = wx.getStorageSync("isLogout");
    if (userinfo) {
      this.setData({
        avatarUrl: userinfo.avatarUrl || "",
        nickname: userinfo.nickname || "",
      });
    } else {
      this.setData({ avatarUrl: "", nickname: "" });
    }
    this.setData({ isLogout: isLogout !== false ? true : false });
  },

  // 只显示一个“微信授权登录”按钮，点击后弹出头像+昵称采集弹窗
  onWeChatLogin() {
    this.setData({ showLoginModal: true });
  },

  // 兼容 mine 页命名，如果未来复用样式/组件
  login() {
    this.onWeChatLogin();
  },

  hideLoginModal() {
    this.setData({ showLoginModal: false });
  },

  changeavatar(e) {
    const linkAvatar = e.detail && e.detail.avatarUrl ? e.detail.avatarUrl : "";
    this.setData({ avatarUrl: linkAvatar });
  },

  onNicknameInput(e) {
    this.setData({ nickname: e.detail.value });
  },

  // 确认登录：校验后执行 wx.login + 后端请求，与 mine 页保持一致
  confirmLogin() {
    if (!this.data.avatarUrl) {
      wx.showToast({ title: "请选择头像", icon: "none" });
      return;
    }
    if (!this.data.nickname) {
      wx.showToast({ title: "请输入昵称", icon: "none" });
      return;
    }
    
    this.hideLoginModal();

    wx.login({
      success: (res) => {
        const code = res.code;
        console.log("code:",code)
        if (!code) {
          wx.showToast({ title: "获取登录凭证失败", icon: "none" });
          return;
        }
        wx.request({
          url: "http://test.uu163yun.com/mapi/Live_2_0/Tourist/Login",
          method: "POST",
          header: {
            'ApiVersion': '6.0',  
            'ApiWay': 'API',  
            'MerId': 'dc529a26P-aecd-4727-86c4-cb62ad24ab99',  
            'VendorId': '350',
          },
          data: {
            code: code,
            endpointCode: "Suse652",
            endpointVersion: "1.0.0",
          },
          success: (response) => {
            if (response.data && response.data.result !== "NG") {
              
            console.log("登录成功")
              const auth = require("../../utils/auth");
              wx.setStorageSync("isLogout", false);
              wx.setStorageSync("userInfo", {
                avatarUrl: this.data.avatarUrl,
                nickname: this.data.nickname,
              });
              const loginResult = {
                userToken: response.data.userToken || "",
                userId: response.data.userId || "",
              };
              wx.setStorageSync("loginResult", loginResult);
              // 记录最近一次服务端校验时间，用于后续 ensureLogin 判定
              try {
                auth.setAuthCheckTime(Date.now());
              } catch (e) {}
              this.setData({
                isLogout: false,
              });
              wx.showToast({ title: "登录成功", icon: "success" });
              // 可选：登录成功后跳转首页或返回
              wx.redirectTo({ url: "/pages/guide/guide" });
            } else {
              wx.showToast({ title: "登录失败，请重试", icon: "none" });
            }
          },
          fail: (error) => {
            console.log("登录失败", error);
            wx.redirectTo({ url: "/pages/guide/guide" });
            //wx.showToast({ title: '登录失败，请重试', icon: 'none' });
          },
        });
      },
      fail: () => {
        wx.showToast({ title: "微信登录失败", icon: "none" });
      },
    });
  },
});
